package cn.jsj.onclock.socket;

import cn.jsj.onclock.interceptor.TokenCensor;
import cn.jsj.onclock.pojo.UserEnt;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.io.Serializable;
import java.util.Map;

/**
 * @author 卢斌
 */
@SuppressWarnings("NullableProblems")
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {


    private final RedisTemplate<String, Serializable> redisTemplate;

    private final TokenCensor tokenCensor;

    @Autowired
    public WebSocketInterceptor(RedisTemplate<String, Serializable> redisTemplate, TokenCensor tokenCensor) {
        this.redisTemplate = redisTemplate;
        this.tokenCensor = tokenCensor;
    }

    /**
     * socket握手拦截器
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {

        // 尝试获取用户传到的token
        String userCode = ((ServletServerHttpRequest) request).getServletRequest().getParameter("userCode");
        if (StringUtil.isNullOrEmpty(userCode)) {
            return false;
        }

        // 检查token是否有效
        Serializable userObject = redisTemplate.opsForValue().get(userCode);
        if (userObject != null) {
            String sessionKey = (String) userObject;
            UserEnt userEnt = tokenCensor.parseToken(userCode, sessionKey);
            if (userEnt == null) {
                return false;
            }

            // 确认token有效后，将用户Id和token写入参数哈希表里
            attributes.put("userId", userEnt.getId());
            attributes.put("token", userCode);
            return true;
        }
        return false;
    }



    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        
    }


}
